package com.hm.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hm.reggie.common.R;
import com.hm.reggie.dto.DishDto;
import com.hm.reggie.entity.Category;
import com.hm.reggie.entity.Dish;
import com.hm.reggie.entity.DishFlavor;
import com.hm.reggie.service.CategoryService;
import com.hm.reggie.service.DishFlavorService;
import com.hm.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping("/dish")
@RestController
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;



    /***
     * 分页获取菜品
     * @return
     */
    @RequestMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //创建分页构造器
        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);

        //创建搜索条件
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<Dish>();
        dishLambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行查找
        Page<Dish> page1 = dishService.page(dishPage, dishLambdaQueryWrapper);

        //拷贝对象,这里只是把分页的page和pageSize拷贝了，具体的list还需要另外拷贝
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //修改list信息
        List<Dish> dishList = page1.getRecords();
        //新建一个空的dishdto的list
        List<DishDto> dishDtoList = new ArrayList<DishDto>();
        for (Dish dish:dishList){
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);//把其他属性拷给dishdto
            Long categoryId = dish.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);//把分类名称拷给dishdto
            log.info("[]"+dishDto.toString());
            dishDtoList.add(dishDto);//把dishdto对象加到list里面去
        }
        log.info("dishDtoList长度："+dishDtoList.size());

        //把dishdto的list设置到page对象里
        dishDtoPage.setRecords(dishDtoList);

        return R.success(dishDtoPage);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     * @RequestBody  DishDto dishDto:把前端传入的json注入到对象里
     */
    @PostMapping
    public R<String> save(@RequestBody  DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        //清理redis里面对应的缓存
        Set keys = redisTemplate.keys("dish_*");
        //String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(keys);
        return R.success("菜品添加成功");
    }

    /***
     * http://localhost:8080/dish/1714937793107562497请求格式
     * 用@PathVariable获取到传参
     * 根据菜品id获取菜品和对应的口味
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){

        return R.success(dishService.getByIdWithFlavor(id));
    }

    /***
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        //清理redis里面对应的缓存
        Set keys = redisTemplate.keys("dish_*");
        //String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    /***
     * http://localhost:8080/dish/status/0?ids=1714937793107562497
     * @param num
     * @param ids
     * @return
     */
    @PostMapping("/status/{num}")
    public R<String> status(@PathVariable Long num, Long[] ids){
        //遍历数组，把status值写进去
        List<Dish> dishList = new ArrayList<>();
        for(Long id :ids){
            Dish dishServiceById = dishService.getById(id);
            dishServiceById.setStatus(num.intValue());
            dishList.add(dishServiceById);
        }
        boolean b = dishService.updateBatchById(dishList);
        return R.success("修改完成");
    }


    /***
     * http://localhost:8080/dish?ids=1714937793107562497
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long[] ids){
        log.info(String.valueOf(ids));
        dishService.removeByIds(Arrays.asList(ids));
        return R.success("已删除！");
    }

    /***
     * http://localhost:8080/dish/list?categoryId=1397844263642378242
     * @param categoryId
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Long categoryId){
//        log.info("categoryId:"+categoryId.toString());
//        //构造条件
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
//        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        //执行查询
//        List<Dish> dishes = dishService.list(queryWrapper);
//        return R.success(dishes);
//    }


    /***
     * 根据分类id获取菜品
     * http://localhost:8080/dish/list?categoryId=1397844263642378242
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId,Integer status){
        String key = "dish_"+categoryId+"_"+status;
        List<DishDto> dtoList = null;
        //查询redis里是否存在数据
        dtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果存在直接获取返回
        if (dtoList != null){
            log.info("redis里面存在数据，不执行查询。");
            return R.success(dtoList);
        }
        //不存在获取后存入redis
        log.info("redis里面不存在数据，执行查询。");

        log.info("categoryId:"+categoryId.toString());
        //构造条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行查询
        List<Dish> dishes = dishService.list(queryWrapper);

        //查询菜品的口味，把他添加到dto对象
        //先进遍历
        dtoList = new ArrayList<DishDto>();
        for (Dish dish : dishes) {
            //创建一个dto对象
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper1);
            log.info("dishFlavors的数量是：{}",dishFlavors.size());
            dishDto.setFlavors(dishFlavors);
            dtoList.add(dishDto);
        }
        log.info(dtoList.size()+"");
        //把数据存入redis
        redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);

        return R.success(dtoList);
    }

}
